package com.sirui.x.learn_security.ctl;

import javax.annotation.Resource;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sirui.x.learn_security.req.LoginRequest;

@RestController
@RequestMapping("/auth")
public class AuthController {

	@Resource
	private AuthenticationManager authenticationManager;


	@PostMapping("/login")
	public String login(@RequestBody LoginRequest loginRequest) {
		Authentication authenticationRequest =
			UsernamePasswordAuthenticationToken.unauthenticated(loginRequest.getUsername(), loginRequest.getPwd());
		Authentication authenticationResponse =
			this.authenticationManager.authenticate(authenticationRequest);

		SecurityContextHolder.getContext().setAuthentication(authenticationResponse);
		return "ok";
	}
	
}
